﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace Oxage.Common
{
	//Reference: http://blog.voidnish.com/?p=238
	public class TextBoxInstantBindingUpdate
	{
		public static DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(TextBoxInstantBindingUpdate), new FrameworkPropertyMetadata(new PropertyChangedCallback(IsEnabledChanged)));

		public static void SetIsEnabled(TextBox target, bool value)
		{
			target.SetValue(TextBoxInstantBindingUpdate.IsEnabledProperty, value);
		}

		public static bool GetIsEnabled(TextBox target)
		{
			return (bool)target.GetValue(IsEnabledProperty);
		}

		private static void IsEnabledChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
		{
			TextBox element = target as TextBox;
			if (element != null)
			{
				if (e.NewValue != null && (bool)e.NewValue)
				{
					element.TextChanged += TextBox_TextChanged;
					element.GotFocus += (sender, args) => { element.SelectAll(); };
				}
				else
				{
					element.TextChanged -= TextBox_TextChanged;
					element.GotFocus -= (sender, args) => { };
				}
			}
		}

		private static void TextBox_TextChanged(object sender, TextChangedEventArgs e)
		{
			TextBox textBox = sender as TextBox;
			if (GetIsEnabled(textBox))
			{
				BindingExpression bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty);
				if (bindingExpression != null)
				{
					bindingExpression.UpdateSource();
				}
			}
		}
	}
}
